//获取app应用
const app = getApp();

Page({
  data: {
    movies: [],
    hiddenLoading: true,
    winHeight: 0,
    start: 0,
    more: false,
  },
  //钩子
  onLoad: function() {
    var that = this;

    //获取屏幕大小
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          winHeight: res.windowHeight
        });
      }
    });
    //调用推荐结构
    that.getHot();
  },
  getHot: function() {
    var that = this;

    //显示loading
    that.setData({
      hiddenLoading: !that.data.hiddenLoading
    });

    //判断cookie中时候有city的缓存
    var city = wx.getStorageSync('city');
    if (city) {
      that.getHotData(city);
    } else {
      //获取用户地理信息
      wx.getLocation({
        success: function(res) {
          //纬度
          var latitude = res.latitude;
          //经度
          var longitude = res.longitude;
          //输出类型
          var output = "json";
          //key 
          var key = "ubnAS9NZvICXBhNbwMF9S5P6eM8hCcIe";

          //当获取到经纬度之后，把经纬度保存到缓存当中去
          wx.setStorageSync('latitude', res.latitude);
          wx.setStorageSync('longitude', res.longitude);

          var url = `http://api.map.baidu.com/geocoder/v2/?location=${latitude},${longitude}&output=${output}&ak=${key}`;

          //根据经纬度获取城市名称  发起请求
          wx.request({
            url: url,
            data: {},
            header: {
              "Content-Type": "json"
            },
            success: function(res) {
              var city = res.data.result.addressComponent.city;
              wx.setStorageSync('city', city);
              if (city) {
                that.getHotData(city);
              }
            }
          })
        },
      })
    }

  },
  getHotData:function(city){
    var that = this;
    var start = that.data.start;

  wx.request({
    url: `https://douban.uieee.com/v2/movie/top250?city=${city}&start=${start}`,
    data:{},
    header:{"Content-Type":"jsno"},
    success:function(res){
      if (JSON.stringify(res.data.subjects) != "[]"){
        //返回有值就追加到movies中
        that.setData({
          start: start + 10,
          hiddenLoading: !that.data.hiddenLoading,
          movies: that.data.movies.concat(res.data.subjects)
        });
      }else{
        that.setData({
          hiddenLoading: !that.data.hiddenLoading,
          more:true
        });
      }
    }
  });

  },
  update: function () {
    var that = this;

    that.setData({
      start: 0,
      hiddenLoading: false,
      movies: [],
      more: false,
    });

    var city = wx.getStorageSync('city');
    that.getHotData(city);

  },
  append:function(){
    var that = this;
    //如果有返回数据
    if(!that.data.more)
    {
      that.setData({
        hiddenLoading:false,
      });
      var city = wx.getStorageInfoSync('city');
      that.getHotData(city);
    }
  },
  onShareAppMessage:function(){
    return{
      title:'电影推荐',
      path: 'pages/hot/hot'
    }
  }


});